package com.mvvm.ktnet.ui.keyEvent

import android.content.Context
import android.media.AudioManager
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.rxLifeScope
import com.android.ktx.view.onClick
import com.blankj.utilcode.util.LogUtils
import com.mvvm.ktnet.R
import com.mvvm.ktnet.base.myappbase.BaseDbActivity
import com.mvvm.ktnet.base.viewmodel.BaseViewModel
import com.mvvm.ktnet.databinding.AcKeycodeBinding
import com.mvvm.ktnet.utils.KeyEventUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch

class EventAc : BaseDbActivity<BaseViewModel, AcKeycodeBinding>() {
    override fun layoutId(): Int = R.layout.ac_keycode

    override fun initView(savedInstanceState: Bundle?) {


        val manager = getSystemService(Context.AUDIO_SERVICE) as AudioManager

        manager.isMusicActive


//        LogUtils.e(manager.isMusicActive)
        if (manager.isMusicActive) {
            mDatabind.play.text = "Pause"
        } else {
            mDatabind.play.text = "Play"
        }
        mDatabind.down.onClick {
            rxLifeScope.launch {
                KeyEventUtils.sendCode2(KeyEvent.KEYCODE_VOLUME_DOWN)
            }
        }
        mDatabind.up.onClick {
            rxLifeScope.launch {
                KeyEventUtils.sendCode2(KeyEvent.KEYCODE_VOLUME_UP)
            }
        }
        mDatabind.play.onClick {
            rxLifeScope.launch {
                if (manager.isMusicActive) {
                    mDatabind.play.text = "Play"
                    KeyEventUtils.sendCode2(KeyEvent.KEYCODE_MEDIA_PAUSE)
                } else {
                    KeyEventUtils.sendCode2(KeyEvent.KEYCODE_MEDIA_PLAY)
                    mDatabind.play.text = "Pause"
                }
//                LogUtils.e(manager.isMusicActive)

            }


        }
        mDatabind.pre.onClick {
            rxLifeScope.launch {
                KeyEventUtils.sendCode2(KeyEvent.KEYCODE_MEDIA_PREVIOUS)
            }
        }
        mDatabind.next.onClick {
            rxLifeScope.launch {
                KeyEventUtils.sendCode2(KeyEvent.KEYCODE_MEDIA_NEXT)
            }
        }
        val testChannel = Channel<Int>()
        rxLifeScope.launch {

            launch {
                repeat(5) {
                    testChannel.send(it)
                    Log.e("main","send $it")
                }
                testChannel.close()
                Log.e("main","send done")
            }
//            Log.e("main","recied ${testChannel.receive()}")

            for (i in testChannel) {
             Log.e("main","recied $i")
            }
            Log.e("main","recied done")
        }
    }

    override fun createObserver() {

    }

    override fun initData() {

    }
}